/*
   CC.NET SideBar Gadget for Windows Vista 
   (C) Simone Chiaretta, 2007
   http://codeclimber.net.nz

   This project is licensed under the new BSD license.
   See the License.txt file for more information.
*/

var xmlHttp;
var timer;

var projectStatus = new Array(0);
var reloadedServers = 0;
var serverList;

function ReloadProjectStatus()
{
   projectStatus = new Array(0);
   reloadedServers = 0;
   serverList = Settings.GetServerList();

   if(serverList.length>0)
   {
      InvokeCCNetXmlStatusReport(serverList[0]);
   }
}

function InvokeCCNetXmlStatusReport(url)
{
	var proxy = new AjaxProxy();
	proxy.RequestXmlStatus(url, processResults, errorHandler);
}

function concatArray(arr1,arr2)
{
   var k = arr1.length;
   for(i in arr2)
   {
      arr1[k++]=arr2[i];
   }
   return arr1;
}

function processResults(projects)
{
   if(projectStatus.length==0)
      projectStatus = projects;
   else
      projectStatus = concatArray(projectStatus,projects);
   reloadedServers++;
   if(reloadedServers == serverList.length)
      RefreshScreen(projectStatus);
   else
   {
      InvokeCCNetXmlStatusReport(serverList[reloadedServers]);
   }
}

function checkUrl()
{
	if(Settings.ProjectList.length==0)
	{
		clearInterval(timer);
		getContentPanel().innerHTML="No project specified. Use the 'Settings' button";
		return false;
		}
	else{
		return true;
	}
}

function getStatusDiv()
{
	return document.getElementById("status");
}

function ChangeGlobalBuildStatus(globalStatus)
{
	globalStatusImg.src="images/global-" + globalStatus + ".png";
}

function getContentPanel()
{
	if(System.Gadget.docked)
		return document.getElementById("contentPanelDocked");
	else
		return document.getElementById("contentPanelUnDocked");
}

function buildRefreshRate()
{
	var interval =  Settings.RefreshInterval;
	if(interval=="")
	{
		interval=30;
	}
	return (interval-0)*1000;
}

function buildDisplayMode()
{
	return  Settings.DisplayMode;
}


function GetStatusImageNameToDisplay(status)
{
	var imageName="";
	if (status=="Failure")
		imageName="error.png";
	else if (status=="Success")
		imageName="check.png";
	else if (status=="Unknown")
		imageName="unknown.png";
	else
		imageName="warning.png";

	return imageName;
}

function GetActivityImageNameToDisplay(activity)
{
	var imageName="";
	if (activity == "CheckingModifications")
		imageName = "gear_view.png";
	else if (activity == "Building")
		imageName = "gear_run.png";
	else if (activity == "Sleeping")
		imageName = "idle.png";
	return imageName;
}

function GetImageToDisplay(project)
{
	var statusImage = GetStatusImageNameToDisplay(project.Status);
	var activityImage = GetActivityImageNameToDisplay(project);

	var finalImage = "";
	if (activityImage == "" || project.Activity == "Sleeping")
		finalImage = statusImage;
	else
		finalImage = activityImage;

	return "<img src=\"images/" + finalImage + "\" />";
}

function GetStatusImageToDisplay(project)
{
	return "<img src=\"images/" + GetStatusImageNameToDisplay(project.Status) + "\" />";
}

function GetActivityImageToDisplay(project)
{
	var activityImage = GetActivityImageNameToDisplay(project.Activity);
	if (activityImage != "")
		return "<img src=\"images/" + activityImage + "\" /> ";
	else
		return "";
}

function errorHandler(message)
{
   var panel = getContentPanel();
   panel.innerHTML="<strong>Server Error</strong>: " + message;
}

function RefreshScreen(projects)
{
     //locate panel DOM element
     var panel = getContentPanel();
     var newContent="";

     if(!System.Gadget.docked)
     {
         var now = new Date();
         newContent="<table cellpadding='0' cellspacing='0'><tr><th>Name</th><th>Status</th><th>Activity</th><th>Last Build Label</th><th>Last Build Time</th><th>&nbsp;</th></tr>"
     }
     
      
      var globalStatus="unknown";
      if(projects.length>0)
          globalStatus="building";
      for (var iNode = 0; iNode < projects.length; iNode++)
      {
         var currentProject=projects[iNode];             
         if(DisplayProject(currentProject))
         {
            if(System.Gadget.docked) 
            {
               var imgTag=GetImageToDisplay(currentProject);
               newContent+="<a href=\""+currentProject.ProjectUrl+"\">"+imgTag+currentProject.Name+"</a>";
            }
            else
            {
               newContent+="<tr><td><a href=\""+currentProject.ProjectUrl+"\">" + currentProject.Name + "</a></td><td class=\"statusCol\">" + GetStatusImageToDisplay(currentProject) + "</td><td class=\"statusCol\">" + GetActivityImageToDisplay(currentProject) + "</td><td>" + currentProject.Label + "</td><td class=\"small\">" + formatDate(currentProject.LastBuildTime) + "</td><td>" + DisplayForceButton(currentProject) + "</td></tr>";
            }
            if(currentProject.Status!="Success")
               globalStatus="failing";
         }
      }

      if(!System.Gadget.docked)
      {
         newContent+="</table>"
      }
      panel.innerHTML=newContent;
      ChangeGlobalBuildStatus(globalStatus);
}

function DisplayForceButton(currentProject)
{
   return "";
   var forceUrl=currentProject.GetBuildUrl();
   var style="";
   if(currentProject.Activity != "Sleeping")
      style=" DISABLED";
   var buttonHtml="<input type=\"button\" value=\"Force\" onClick=\"forceBuild('" + forceUrl + "');\" " + style + "/>";
   return buttonHtml;
}

function getForceUrl(url)
{
   return url;
}

function IsProjectIncluded(project)
{
   for(i in Settings.ProjectList)
   {
      if(project.Name==Settings.ProjectList[i].projectName && project.ServerUrl==Settings.ProjectList[i].serverUrl)
         return true;
   }
   return false;
}

function DisplayProject(project)
{
   if(IsProjectIncluded(project))
   {
	   var displayMode = buildDisplayMode();
      
	   switch(displayMode)
	   {
		   case DisplayModeEnum.All:
			   return true;
			   break;
		   case DisplayModeEnum.OnlyFailing:
			   if(project.Status!="Success")
				   return true;
			   else
				   return false;
			   break;
	   }
	}
}


function trim(string)
{
	return string.replace(/(\s+$)|(^\s+)/g, '');
}

function formatDate(dateStr)
{
	var dd = new Date.W3CDTF();
	dd.setW3CDTF( dateStr );
	return dd.toLocaleString();
}

function initTimer()
{
   Settings.Read();
  
	if(!checkUrl())
	{
		return;
	}
	
	var interval =   buildRefreshRate();
	ReloadProjectStatus();
	clearInterval(timer);
	timer  = setInterval(ReloadProjectStatus, interval);
}

function init()
{
	System.Gadget.onUndock = undock;
	System.Gadget.onDock = dock;
	bindState(); 
	initTimer();
}

function bindState()
{
	if(System.Gadget.docked) 
	{
		this.dock();
	} 
	else
	{
		this.undock(); 
	}
}

function undock()
{
	with(document.body.style)
		width=550,
		height=139;

	containerPanelDocked.style.display = 'none';
	containerPanelUnDocked.style.display = 'block';

	dockedCcnetBg.style.display = 'none';
	undockedCcnetBg.style.display = 'block';

   refreshView(); 
}


function dock()
{
	with(document.body.style)
		width=130,
		height=139;

	containerPanelDocked.style.display = 'block';
	containerPanelUnDocked.style.display = 'none';

	dockedCcnetBg.style.display = 'block';
	undockedCcnetBg.style.display = 'none';
	refreshView();
}

function refreshView()
{
   Settings.Read();
   if(checkUrl())
   {
	   var panel = getContentPanel();
	   resetScrollPosition(panel);
	   panel.innerHTML="Loading...";
      ChangeGlobalBuildStatus("unknown");
	   RefreshScreen(projectStatus);
	}
}
